<template>
  <div class="version-management">
    <!-- 主体内容区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">🚀 版本管理</span>
          <div class="header-actions">
            <div class="record-stats">
              <el-tag type="info">共 {{ total }} 个版本</el-tag>
            </div>
            <div class="action-buttons">
              <el-button type="primary" @click="handleAdd" :icon="Plus">
                ➕ 发布新版本
              </el-button>
            </div>
          </div>
        </div>
      </template>
      
      <div class="table-container">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          :height="tableHeight"
          class="custom-table"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="version" label="版本号" width="120" />
          <el-table-column prop="latestVersion" label="最新版本" width="120" />
          <el-table-column prop="updateLog" label="更新日志" width="200" show-overflow-tooltip />
        <!--  <el-table-column prop="downloadUrl" label="下载地址" width="140" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link type="primary" :href="formatDownloadUrl(row.downloadUrl)" target="_blank" v-if="row.downloadUrl">
                📥 下载链接
              </el-link>
              <span v-else class="text-gray">暂无下载链接</span>
            </template>
          </el-table-column>-->
          <el-table-column prop="forceUpdate" label="强制更新" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="(row.forceUpdate === 1 || row.forceUpdate === true) ? 'danger' : 'success'" size="small">
                {{ (row.forceUpdate === 1 || row.forceUpdate === true) ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="updateTime" label="更新时间" width="180" />
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="handleDelete(row)">
                🗑️ 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pageCurrent"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 发布新版本弹窗 -->
    <el-dialog
      v-model="showVersionModal"
      title="➕ 发布新版本"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="versionForm" :rules="versionRules" ref="versionFormRef" label-width="120px">
        <el-form-item label="版本号" prop="version">
          <el-input-number v-model="versionForm.version" :precision="1" :step="0.1" :min="0.1" placeholder="版本号" />
        </el-form-item>
        <el-form-item label="更新日志" prop="updateLog">
          <el-input 
            v-model="versionForm.updateLog" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入更新日志" 
          />
        </el-form-item>
        <el-form-item label="应用文件" prop="file">
          <el-upload
            ref="uploadRef"
            :show-file-list="true"
            :file-list="fileList"
            :before-upload="handleBeforeUpload"
            :on-remove="handleFileRemove"
            :on-change="handleFileChange"
            :auto-upload="false"
            :limit="1"
            accept=".apk,.ipa,.zip,.exe"
            class="upload-area"
          >
            <el-button type="primary" :icon="Plus">
              📁 选择应用文件
            </el-button>
            <template #tip>
              <div class="upload-tip">
                <el-text type="info" size="small">
                  支持格式：APK、IPA、ZIP、EXE 文件，最大 100MB，只能选择一个文件
                </el-text>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeVersionModal">取消</el-button>
          <el-button type="primary" @click="confirmVersion" :loading="confirmLoading">
            {{ confirmLoading ? '保存中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { queryVersionListPage, deleteVersion, uploadApp } from '../api/business.js'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const pageSize = ref(10)
const pageCurrent = ref(1)

// 弹窗相关
const showVersionModal = ref(false)
const confirmLoading = ref(false)
const versionFormRef = ref()

// 文件上传相关
const uploading = ref(false)
const uploadRef = ref()
const fileList = ref([])
const selectedFile = ref(null)

// 版本表单
const versionForm = reactive({
  version: 0.1,
  updateLog: ''
})

// 表单验证规则
const versionRules = {
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  updateLog: [
    { required: true, message: '请输入更新日志', trigger: 'blur' }
  ]
}

// 加载管理器
let loadingInstance = null
const showLoading = (text = '加载中...') => {
  if (loadingInstance) {
    loadingInstance.close()
  }
  loadingInstance = ElLoading.service({
    lock: true,
    text: text,
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

const hideLoading = () => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

// 计算表格高度
const tableHeight = computed(() => {
  return 'calc(100vh - 280px)'
})

// 获取版本列表数据
const getData = async () => {
  loading.value = true
  
  try {
    const params = {
      pageNum: pageCurrent.value,
      pageSize: pageSize.value
    }
    
    const res = await queryVersionListPage(params)
    console.info('版本列表数据:', res)
    
    if (res && res.success === true && res.content) {
      tableData.value = res.content.list || []
      total.value = res.content.total || 0
      
      ElMessage.success(`🚀 成功获取${tableData.value.length}个版本`)
    } else {
      throw new Error(res?.message || '数据格式错误')
    }
  } catch (error) {
    console.error('获取版本列表失败:', error)
    ElMessage.error(error.data?.message || '获取版本列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  getData()
}

const handleCurrentChange = (page) => {
  pageCurrent.value = page
  getData()
}

// 重置表单
const resetVersionForm = () => {
  versionForm.version = 0.1
  versionForm.updateLog = ''
  fileList.value = []
  selectedFile.value = null
}

// 新增版本
const handleAdd = () => {
  resetVersionForm()
  showVersionModal.value = true
}

// 删除版本
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除版本 "${row.version}" 吗？删除后无法恢复。`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    showLoading('删除中...')
    
    // 使用批量删除接口，传入数组格式的ID
    const res = await deleteVersion([row.id])
    
    hideLoading()
    
    // 检查接口返回的success字段
    if (res && res.success === true) {
      ElMessage.success('✅ 删除成功')
      
      // 刷新列表
      setTimeout(() => {
        getData()
      }, 500)
    } else {
      // 接口返回失败
      throw new Error(res?.message || '删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      hideLoading()
      console.error('删除版本失败:', error)
      ElMessage.error('❌ ' + (error.message || error.data?.message || '删除失败'))
    }
  }
}

// 关闭弹窗
const closeVersionModal = () => {
  showVersionModal.value = false
  resetVersionForm()
  if (versionFormRef.value) {
    versionFormRef.value.clearValidate()
  }
}

// 确认保存版本
const confirmVersion = async () => {
  if (!versionFormRef.value) return
  
  try {
    await versionFormRef.value.validate()
    
    // 检查是否选择了文件
    if (!selectedFile.value) {
      ElMessage.error('❌ 请选择应用文件')
      return
    }
    
    confirmLoading.value = true
    showLoading('上传中...')
    
    // 使用新的上传应用接口
    const res = await uploadApp(selectedFile.value, versionForm.version, versionForm.updateLog)
    
    hideLoading()
    
    // 检查接口返回的success字段
    if (res && res.success === true) {
      ElMessage.success('✅ 版本发布成功')
      closeVersionModal()
      
      // 刷新列表
      setTimeout(() => {
        getData()
      }, 500)
    } else {
      // 接口返回失败
      throw new Error(res?.message || '版本发布失败')
    }
    
  } catch (error) {
    hideLoading()
    if (error.message && error.message.includes('请输入')) {
      // 表单验证错误，不显示错误消息
      return
    }
    
    console.error('版本发布失败:', error)
    
    // 显示详细错误信息
    let errorMessage = error.message || error.data?.message || '版本发布失败'
    
    ElMessage.error('❌ ' + errorMessage)
  } finally {
    confirmLoading.value = false
  }
}

// 文件上传前验证
const handleBeforeUpload = (file) => {
  // 检查文件类型
  const allowedTypes = ['.apk', '.ipa', '.zip', '.exe']
  const fileName = file.name.toLowerCase()
  const isValidType = allowedTypes.some(type => fileName.endsWith(type))
  
  if (!isValidType) {
    ElMessage.error('❌ 文件格式不支持，请选择 APK、IPA、ZIP 或 EXE 文件')
    return false
  }
  
  // 检查文件大小（100MB）
  const isValidSize = file.size / 1024 / 1024 < 100
  if (!isValidSize) {
    ElMessage.error('❌ 文件大小不能超过 100MB')
    return false
  }
  
  // 保存选中的文件
  selectedFile.value = file
  return false // 阻止自动上传
}

// 文件移除处理
const handleFileRemove = () => {
  selectedFile.value = null
}

// 文件选择变化处理
const handleFileChange = (file, fileList) => {
  if (file && file.raw) {
    // 验证文件
    const allowedTypes = ['.apk', '.ipa', '.zip', '.exe']
    const fileName = file.name.toLowerCase()
    const isValidType = allowedTypes.some(type => fileName.endsWith(type))
    
    if (!isValidType) {
      ElMessage.error('❌ 文件格式不支持，请选择 APK、IPA、ZIP 或 EXE 文件')
      // 清除无效文件
      fileList.splice(fileList.indexOf(file), 1)
      return
    }
    
    // 检查文件大小（100MB）
    const isValidSize = file.size / 1024 / 1024 < 100
    if (!isValidSize) {
      ElMessage.error('❌ 文件大小不能超过 100MB')
      // 清除无效文件
      fileList.splice(fileList.indexOf(file), 1)
      return
    }
    
    // 保存选中的文件
    selectedFile.value = file.raw
    console.log('文件选择成功:', file.name, selectedFile.value)
  }
}

// 处理下载链接格式化
const formatDownloadUrl = (url) => {
  if (!url) return ''
  
  // 获取后端访问前缀（可以从环境变量或配置中获取）
  const baseUrl = import.meta.env.VITE_API_BASE_URL || '/api'
  
  // 如果链接以 / 开头，去掉开头的 /
  let formattedUrl = url.startsWith('/') ? url.substring(1) : url
  
  // 如果链接已经是完整的URL（包含http或https），直接返回
  if (formattedUrl.startsWith('http://') || formattedUrl.startsWith('https://')) {
    return formattedUrl
  }
  
  // 拼接后端访问前缀
  return `${baseUrl}/${formattedUrl}`
}

// 组件挂载时初始化
onMounted(() => {
  getData()
})
</script>

<style scoped>
.version-management {
  background: #f5f7fa;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  padding-bottom: 70px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 700;
  color: #1e40af;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.record-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.custom-table {
  width: 100%;
  flex: 1;
}

.pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  z-index: 10;
}

.text-gray {
  color: #909399;
  font-size: 12px;
}

/* 表格滚动条样式 */
:deep(.el-table) {
  height: 100% !important;
}

:deep(.el-table__body-wrapper) {
  /* 只在需要时显示滚动条 */
  overflow-y: auto !important;
  overflow-x: hidden !important;
  max-height: calc(100vh - 350px) !important;
  /* 为底部分页器预留更多空间，避免遮挡 */
  padding-bottom: 10px !important;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
  transition: background 0.3s ease;
  min-height: 20px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-corner {
  background: #f5f5f5;
}

/* 表格横向铺满 */
:deep(.el-table) {
  width: 100% !important;
  min-width: 100% !important;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__footer-wrapper) {
  width: 100% !important;
}

/* 确保表格内容不会超出容器 */
:deep(.el-table__header),
:deep(.el-table__body) {
  width: 100% !important;
  table-layout: fixed;
}

/* 表格单元格内容溢出处理 */
:deep(.el-table .cell) {
  word-break: break-word;
  word-wrap: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 确保最后一行数据不被遮挡 */
:deep(.el-table__body tr:last-child td) {
  border-bottom: 1px solid #ebeef5;
}

/* 弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 文件上传样式 */
.download-url-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.url-input {
  flex: 1;
}

.upload-button {
  flex-shrink: 0;
}

.upload-tip {
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .version-management {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}
</style>